import { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { toast } from 'react-hot-toast';
import { WithAuth } from "../../lib/authutils";
import PageTitle from '../../components/page-title';
import Button from '../../components/button';
import { ThemeContext } from '../../layouts/layout';
import { useContext } from 'react';
import { getSeverityClass, severityColors, statusColors } from '../../lib/data/definitions-customer';
import { getProjectVulnerability } from '../../lib/data/api';
import { getVulnerabilityStatusColor, formatDate, createMarkup } from '../../lib/utilities';
import { 
  ChevronLeftIcon,
  ShieldExclamationIcon,
  ExclamationTriangleIcon,
  DocumentTextIcon,
  LockClosedIcon,
  ClipboardDocumentListIcon,
  LinkIcon,
  ArrowPathIcon,
  CheckCircleIcon,
  MagnifyingGlassIcon,
  ChevronLeftIcon as ChevronLeftIconSolid,
  ChevronRightIcon
} from '@heroicons/react/24/outline';

// Define the Vulnerability interface based on API response
interface VulnerabilityInstance {
  id: number;
  URL: string;
  Parameter: string;
  status: string;
}

interface VulnerabilityDetails {
  id: number;
  vulnerabilityname: string;
  vulnerabilityseverity: string;
  cvssscore: number;
  cvssvector: string;
  status: string;
  vulnerabilitydescription: string;
  POC: string | null;
  created: string;
  vulnerabilitysolution: string;
  vulnerabilityreferlnk: string;
  project: number;
  created_by: string;
  last_updated_by: string;
  cwe: string[];
  published: boolean;
  instance: VulnerabilityInstance[];
}

const CustomerVulnerabilityView: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState<boolean>(true);
  const [vulnerability, setVulnerability] = useState<VulnerabilityDetails | null>(null);
  const theme = useContext(ThemeContext);
  const darkMode = theme === 'dark';
  
  // Table pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [instancesPerPage] = useState(5);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    const fetchVulnerabilityDetails = async () => {
      setLoading(true);
      try {
        const data = await getProjectVulnerability(id);
        if (data) {
          setVulnerability(data);
        } else {
          toast.error('Vulnerability details not found');
          navigate(-1);
        }
      } catch (error) {
        console.error('Error fetching vulnerability details:', error);
        toast.error('Error loading vulnerability details');
      } finally {
        setLoading(false);
      }
    };

    fetchVulnerabilityDetails();
  }, [id, navigate]);

  // Function to get severity background class with opacity
  const getSeverityBgClass = (severity: string): string => {
    switch (severity) {
      case 'Critical':
        return 'bg-red-50 dark:bg-red-900/20';
      case 'High':
        return 'bg-orange-50 dark:bg-orange-900/20';
      case 'Medium':
        return 'bg-yellow-50 dark:bg-yellow-900/20';
      case 'Low':
        return 'bg-blue-50 dark:bg-blue-900/20';
      default:
        return 'bg-gray-50 dark:bg-gray-900/20';
    }
  };

  // Format CVSS vector for display
  const formatCVSSVector = (vector: string): string => {
    return vector.replace('CVSS:3.1/', '');
  };

  // Filter instances based on search term
  const filteredInstances = useMemo(() => {
    if (!vulnerability?.instance) return [];
    return vulnerability.instance.filter(
      instance => 
        instance.URL.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (instance.Parameter && instance.Parameter.toLowerCase().includes(searchTerm.toLowerCase())) ||
        instance.status.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [vulnerability, searchTerm]);

  // Get current instances for pagination
  const indexOfLastInstance = currentPage * instancesPerPage;
  const indexOfFirstInstance = indexOfLastInstance - instancesPerPage;
  const currentInstances = filteredInstances.slice(indexOfFirstInstance, indexOfLastInstance);
  
  // Calculate total pages
  const totalPages = Math.ceil(filteredInstances.length / instancesPerPage);

  return (
    <div className="mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <div className="flex items-center mb-6">        <Button 
          onClick={() => navigate(-1)}
          className="!px-2 mr-3 bg-gray-200 hover:bg-gray-300 text-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600 dark:text-white"
          data-testid="back-button"
        >
          <ChevronLeftIcon className="h-5 w-5" />
        </Button>
        <PageTitle title={vulnerability ? vulnerability.vulnerabilityname : "Vulnerability Details"} />
      </div>

      {loading ? (
        <div className="flex justify-center items-center py-20">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
        </div>
      ) : vulnerability ? (
        <div className={`rounded-lg shadow-sm border ${darkMode ? 'border-gray-700' : 'border-gray-200'}`}>
          {/* Header section with title and severity */}
          <div className={`rounded-t-lg p-5 ${getSeverityBgClass(vulnerability.vulnerabilityseverity)}`}>
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div className="flex-1">                <div className="flex flex-wrap items-center gap-3 text-sm mt-1">
                  {/* Severity badge */}
                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${severityColors[vulnerability.vulnerabilityseverity]}`}>
                    <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
                    {vulnerability.vulnerabilityseverity}
                  </span>
                  
                  {/* Status badge */}
                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${statusColors[vulnerability.status]}`}>
                    {vulnerability.status === 'Confirm Fixed' ? (
                      <CheckCircleIcon className="h-4 w-4 mr-1" />
                    ) : (
                      <ShieldExclamationIcon className="h-4 w-4 mr-1" />
                    )}
                    {vulnerability.status}
                  </span>
                  
                  {/* CVSS Score */}
                  <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800 border border-gray-300 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600">
                    <LockClosedIcon className="h-4 w-4 mr-1" />
                    CVSS {vulnerability.cvssscore}
                  </span>
                  
                  {/* CWEs - Handle multiple CWEs */}
                  {vulnerability.cwe && vulnerability.cwe.length > 0 && (
                    <div className="flex flex-wrap items-center gap-2">
                      {vulnerability.cwe.map((cweEntry, index) => (
                        <span 
                          key={index}
                          className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-100 text-purple-800 border border-purple-300 dark:bg-purple-900 dark:text-purple-300 dark:border-purple-600"
                        >
                          <ClipboardDocumentListIcon className="h-4 w-4 mr-1" />
                          {cweEntry.split(':')[0]}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Main content */}
          <div className="p-6 space-y-8">
            {/* CVSS Details */}
            <section className="space-y-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <LockClosedIcon className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                CVSS Details
              </h2>
              <div className={`p-4 rounded-lg border ${darkMode ? 'border-gray-700 bg-gray-800/50' : 'border-gray-200 bg-gray-50'}`}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <p className="text-sm text-gray-500 dark:text-gray-400">CVSS Score:</p>
                    <p className="font-medium text-gray-900 dark:text-white">{vulnerability.cvssscore}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500 dark:text-gray-400">CVSS Vector:</p>
                    <p className="font-medium text-gray-900 dark:text-white font-mono text-xs">
                      {formatCVSSVector(vulnerability.cvssvector)}
                    </p>
                  </div>
                </div>
              </div>
            </section>

            {/* Description */}
            <section className="space-y-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <DocumentTextIcon className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                Description
              </h2>
              <div className={`prose prose-stone ${darkMode ? 'prose-invert' : ''} max-w-none text-gray-800 dark:text-gray-200`} 
                dangerouslySetInnerHTML={createMarkup(vulnerability.vulnerabilitydescription)} />
            </section>

            {/* Solution */}
            <section className="space-y-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <ArrowPathIcon className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                Solution
              </h2>
              <div className={`prose prose-stone ${darkMode ? 'prose-invert' : ''} max-w-none text-gray-800 dark:text-gray-200`} 
                dangerouslySetInnerHTML={createMarkup(vulnerability.vulnerabilitysolution)} />
            </section>

            {/* References */}
            <section className="space-y-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <LinkIcon className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                References
              </h2>
              <div className={`prose prose-stone ${darkMode ? 'prose-invert' : ''} max-w-none text-gray-800 dark:text-gray-200`} 
                dangerouslySetInnerHTML={createMarkup(vulnerability.vulnerabilityreferlnk)} />
            </section>

            {/* Affected URLs/Instances with pagination and search */}
            {vulnerability.instance && vulnerability.instance.length > 0 && (
              <section className="space-y-4">
                <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                  <ShieldExclamationIcon className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                  Affected URLs
                </h2>
                
                {/* Search input */}
                <div className="relative max-w-md mb-4">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <MagnifyingGlassIcon className="w-5 h-5 text-gray-500 dark:text-gray-400" />
                  </div>
                  <input
                    type="search"
                    className={`block w-full p-2 pl-10 text-sm border rounded-lg focus:ring-blue-500 focus:border-blue-500 ${
                      darkMode ? 'bg-gray-800 border-gray-700 text-white' : 'bg-white border-gray-300 text-gray-900'
                    }`}
                    placeholder="Search instances..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
                
                {/* Instances table with pagination */}
                <div className={`overflow-x-auto border rounded-lg ${darkMode ? 'border-gray-700' : 'border-gray-200'}`}>
                  <table className="min-w-full divide-y divide-gray-300 dark:divide-gray-700">
                    <thead>
                      <tr className={darkMode ? 'bg-gray-800/50' : 'bg-gray-50'}>
                        <th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">URL</th>
                        <th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Parameter</th>
                        <th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                      {currentInstances.map((instance) => (
                        <tr key={instance.id} className={darkMode ? 'bg-gray-900' : 'bg-white'}>
                          <td className="px-4 py-4 text-sm text-gray-900 dark:text-white break-all">
                            {instance.URL}
                          </td>
                          <td className="px-4 py-4 text-sm text-gray-900 dark:text-white">
                            {instance.Parameter || '-'}
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border-2 ${getVulnerabilityStatusColor(instance.status)}`}>
                              {instance.status}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  
                  {/* Pagination controls */}
                  <div className={`px-4 py-3 flex items-center justify-between border-t ${darkMode ? 'border-gray-700 bg-gray-900' : 'border-gray-200 bg-white'}`}>
                    <div>
                      <p className="text-sm text-gray-700 dark:text-gray-300">
                        Showing <span className="font-medium">{indexOfFirstInstance + 1}</span> to{" "}
                        <span className="font-medium">
                          {Math.min(indexOfLastInstance, filteredInstances.length)}
                        </span>{" "}
                        of <span className="font-medium">{filteredInstances.length}</span> entries
                      </p>
                    </div>
                    
                    <div className="flex items-center space-x-2">
                      <button
                        className={`flex items-center px-2 py-1 rounded text-sm font-medium ${
                          currentPage === 1 
                            ? "bg-gray-200 text-gray-500 cursor-not-allowed dark:bg-gray-700 dark:text-gray-400" 
                            : "bg-gray-200 text-gray-800 hover:bg-gray-300 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-600"
                        }`}
                        onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                        disabled={currentPage === 1}
                      >
                        <ChevronLeftIconSolid className="h-4 w-4" />
                      </button>
                      <span className="px-3 py-1 text-sm text-gray-700 dark:text-gray-300">
                        {currentPage} / {Math.max(1, totalPages)}
                      </span>
                      <button
                        className={`flex items-center px-2 py-1 rounded text-sm font-medium ${
                          currentPage === totalPages || totalPages === 0
                            ? "bg-gray-200 text-gray-500 cursor-not-allowed dark:bg-gray-700 dark:text-gray-400" 
                            : "bg-gray-200 text-gray-800 hover:bg-gray-300 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-600"
                        }`}
                        onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                        disabled={currentPage === totalPages || totalPages === 0}
                      >
                        <ChevronRightIcon className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>
              </section>
            )}

            {/* Proof of Concept (if available) */}
            {vulnerability.POC && (
              <section className="space-y-4">
                <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                  <ExclamationTriangleIcon className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                  Proof of Concept
                </h2>
                <div className={`prose prose-stone ${darkMode ? 'prose-invert' : ''} max-w-none text-gray-800 dark:text-gray-200`} 
                  dangerouslySetInnerHTML={createMarkup(vulnerability.POC)} />
              </section>
            )}
          </div>
        </div>
      ) : (
        <div className="text-center py-10">
          <p className="text-gray-500 dark:text-gray-400">
            Vulnerability details not found
          </p>
        </div>
      )}
    </div>
  );
};

export default WithAuth(CustomerVulnerabilityView);